import { computed, ref } from "vue";
import Compressor from 'compressorjs';
import useChatStore from '@/store/modules/chat';

const SUPPORT_FILES = [
  '.pdf',
  '.doc',
  '.txt',
  '.xls',
  '.ppt',
  '.docx',
  '.xlsx',
  '.pptx',
  '.c',
  '.cpp',
  '.h',
  '.hpp',
  '.java',
  '.py',
  '.js',
  '.ts',
  '.html',
  '.css',
  '.json',
  '.xml',
  '.php',
];


export function useUpload() {
  const chatStore = useChatStore();
  const isConversation = computed(() => chatStore.isConversation);
  const customFiles = ref([]);
  const isUpload = computed(() => {
    let count = 0;
    customFiles.value.forEach(item => {
      if(item.uploaded === false) {
        count+=1
      }
    })

    return count === 0
  });


  function getThumb(type, fullPath) {
    const [filType, name] = type.split('/')
    const mimeMap = {
      pdf: 'affix',
      doc: 'doc',
      txt: 'affix',
      xls: 'affix',
      ppt: 'pptx',
      docx: 'affix',
      xlsx: 'affix',
      pptx: 'affix',
      c: 'affix',
      cpp: 'affix',
      h: 'affix',
      hpp: 'affix',
      java: 'affix',
      py: 'affix',
      js: 'affix',
      ts: 'affix',
      html: 'affix',
      css: 'affix',
      json: 'affix',
      xml: 'affix',
      php: 'affix',
    }
    return filType === 'image' ? fullPath : `/static/mimes/${mimeMap[name] || 'affix'}.png`
  }


  const handleUpload = ({ tempFiles }, type) => {
    debugger;
    tempFiles.forEach(async (file) => {
      customFiles.value.push({ file, uploaded: false })
      const resp = await chatStore.uploadFile({ file: file })

      const result = JSON.parse(resp.data)
      customFiles.value = customFiles.value.map((item) => {
        if (item.file.name === file.name) {
          return Object.assign(item, {
            filePath: result.filePath,
            uploaded: true,
            type,
            imageThumb: getThumb(file.type, result.filePath),
          })
        }
        return item
      })

    });
  }

  const handleChooseImage = () => {
    if (isConversation.value) {
      return;
    }
    uni.chooseImage({
      count: 9,
      sourceType: ['camera', 'album'],
      success: (file) => handleUpload(file, 0),
      fail: err => {
        console.log('chooseImage fail', err);
      },
    });
  };


  function handleChooseFiles() {
    if (isConversation.value) {
      return;
    }
    uni.chooseFile({
      count: 6,
      extension: SUPPORT_FILES,
      success: (file) => handleUpload(file,1),
      fail: err => {
        console.log('chooseFile fail', err);
      },
    });
  }

  const handleRemoveFile = (index) => {
    customFiles.value = customFiles.value.filter((_,i) => i !== index)
  }

  return {
    isUpload,
    customFiles, handleChooseImage, handleChooseFiles,
    handleRemoveFile
  }
}